package com.ggb.reactive.handler

import com.ggb.reactive.extension.thisLogger
import org.springframework.stereotype.Component
import org.springframework.web.reactive.socket.WebSocketHandler
import org.springframework.web.reactive.socket.WebSocketMessage
import org.springframework.web.reactive.socket.WebSocketSession
import reactor.core.publisher.Mono
import java.util.concurrent.ConcurrentHashMap

@Component
class WebSocketHandler : WebSocketHandler {

    private val sessionMap = ConcurrentHashMap<String, WebSocketSession>()

    override fun handle(session: WebSocketSession): Mono<Void> {
        val path = session.handshakeInfo.uri.path
        val sid = path.substringAfterLast("/")
        sessionMap[sid] = session
        //val output = Flux.interval(Duration.ofSeconds(1))
        //    .map { session.textMessage("Echo: $it") }
        val input = session.receive()
            .map(WebSocketMessage::getPayloadAsText)
            .doOnNext { message -> println("Received message from $sid: $message") }
            .map { message -> session.textMessage("Received: $message") }

        //return session.send(output).and(session.send(input)).then()
        return session.send(input).then()
    }

    fun sendToAllClient(message: String) {
        sessionMap.values.forEach { session ->
            try {
                session.send(Mono.just(session.textMessage(message))).subscribe()
            } catch (e: Exception) {
                thisLogger().error("[WebSocket发送异常] 原因是",e)
            }
        }
    }
}
